#!/usr/bin/env python3

import os
import sys
import shutil
import ipsw
import platform
import argparse
import device
import restore
import ipsw
import device as localdevice
import utils

tool_version = '\033[92m' + "1.0.1" + '\033[0m' # Leave outside so we have it at an obvious spot to find later


if __name__ == "__main__":
    argv = sys.argv

    text = 'Vieux - A tool for 32/64 Bit OTA downgrades by Matty, @mosk_i'
    parser = argparse.ArgumentParser(description = text, usage="vieux -i 'PATH/TO/.ipsw'")
    parser.add_argument('-c', '--clean', help='Clean up any leftover files', action='store_true')
    parser.add_argument("-i", "--ipsw", help="Path to IPSW file", nargs=1)
    parser.add_argument('-k', '--kdfu', help='"Path/To/patchediBSS" Enter KDFU mode (32 Bit Only, device must be jailbroken)', nargs=1, metavar="iBSS")
    parser.add_argument("-l", "--list", help="List what devices can be restored to what iOS versions", action="store_true")
    parser.add_argument('-p', '--pwn', help='Enter PWNDFU mode, which will also apply sig patches (64 Bit Only)', action='store_true')
    parser.add_argument('-r', '--restore', help='(Coming soon) "Path/To/.ipsw" Just restore to a custom ipsw', nargs=1, metavar='IPSW')
    parser.add_argument('-s', '--shsh', help='"Path/To/Save/Location/" Save OTA blobs to a given path for future use (64 Bit Only)', nargs=1, metavar='PATH')
    parser.add_argument("-v", "--version", help="List the version of the tool", action="store_true")
    parser.add_argument("-y", "--credits", help="List credits and Big Yoshi", action="store_true")


    if platform.system() == 'Darwin': # If not MacOS
        pass
    elif platform.system() == "Linux":
        sys.exit('\033[91m' + "\nSorry this OS is not currently supported!\n\nOnly MacOS machines (Hackintosh or a legitimate Apple computer) are support as of now.\n" + '\033[0m')
    elif platform.system() == "Windows":
        sys.exit('\033[91m' + "\nSorry Windows will never be supported!\n\nOnly MacOS machines (Hackintosh or a legitimate Apple computer) are support as of now.\n" + '\033[0m')

    if len(argv) == 1:
        parser.print_help(sys.stderr)
        sys.exit(1)

    args = parser.parse_args()

    if args.clean:
        utils.yoshi()
        utils.clean()
        exit(22)
    if args.credits:
        print("\n                                            Big Yoshi :)")
        utils.yoshi()
        print("Created by: Matty - @mosk_i\n")
        print("Lots of help by: Merc - @Vyce_Merculous\n")
        print("Thanks to, axi0mX, Tihmstar, Linus Henze, geohotz for their respective works\n")
        print("Thanks to Xerus - @xerusdesign and @Schnob for testing\n\n")
        sys.exit()
    elif args.pwn:
        utils.yoshi()
        print('\033[91m' + "Do not use this option if you are wanting to do an OTA downgrade.\nReboot your device into normal DFU mode and run './vieux -i path/to/.ipsw' and let that exploit the device if you want to downgrade to 10.3.3." + '\033[0m')
        print("Only use this option for other things that require PWNDFU mode...")
        print("Connect 64 Bit device in DFU mode...")
        restore.pwndfumode()
        exit(22)
    elif args.shsh:
        utils.yoshi()
        print("64 ONLY CURRENTLY\nCONNECT DEVICE IN DFU MODE...")
        ecid = device.getecid()
        device = device.getmodel()
        seperate = True
        print("BE WARNED THIS WILL TAKE AROUND 1-2 MINUTES...")
        print("DON'T WORRY IF IT LOOKS LIKE NOTHING IS HAPPENING...")
        pathf = restore.saveshsh(argv[2], ecid, device, seperate)
        print("SHSH saved to: " + pathf)
        print("In the case Apple unsigns 10.3.3 OTA and you need to use these SHSH, I will update Vieux to allow for the use of these backed up SHSH")
        print("For now they should have no use as you can just use Vieux to downgrade! But it is good to be prepared for the worst")
        exit(22)
    elif args.restore:
        utils.yoshi()
        print("Coming soon...")
        exit(22)
    elif args.ipsw:
        utils.yoshi()
        print('\033[95m' + "Vieux - A tool for 32/64 Bit OTA downgrades\n" + '\033[0m')
        print("Current version is: " + tool_version)
        print("If you are using a 64 Bit device then connect it in " + '\033[91m' + "DFU" + '\033[0m' + " Mode\nIf you are using a 32 Bit device then just have it connected in " + '\033[91m' + "NORMAL" + '\033[0m' + " mode")
        ipsw.removeFiles()
        ipsw.unzipIPSW(argv[2])

    elif args.kdfu:
        utils.yoshi()
        print("Entering kDFU mode")
        kloaderlocation = "resources/bin/kloader"
        kloaderlocation10 = "resources/bin/kloader10"
        ibssnew = str(argv[2])
        if not os.path.exists(ibssnew):
            print(f"File not found at {ibssnew}")
            exit(2)
        else:
            with open(ibssnew, "rb") as f:
                if b'iBSS for' in f.read():
                    print("Found valid iBSS file")
                    f.close()
                    localdevice.enterkdfumode(kloader= kloaderlocation, kloader10=kloaderlocation10, ibss=ibssnew)
                else:
                    f.close()
                    print("Not a valid iBSS file, try again with a valid iBSS file")
                    exit(22)
        exit(2)

    elif args.list:
        print("Currently supported device:\n")
        for devices in device.supported():
            print(f"Device {devices['device']}, iOS {devices['version']}")
        sys.exit()

    elif args.version:
        sys.exit(f"Current version is: {tool_version}")

    else:
        sys.exit(f'{argv[1]} is not a valid argument!')

    utils.clean()
    print('\033[92m' + ''"Finished! Enjoy your downgraded device :)" + '\033[0m')
    sys.exit(0)
